/**
 * 扫码工具函数
 * @param {Object} options 扫码配置
 * @returns {Promise}
 */
const scanCodeUtils = (options = {}) => {
	return new Promise((resolve, reject) => {
		const defaultOptions = {
			scanType: ['qrCode'],
			onlyFromCamera: true,
			success: (res) => {
				console.log('扫码成功:', res);
				// 对结果进行统一处理
				const processedResult = {
					code: res.result,
					type: res.scanType,
					charSet: res.charSet,
					imagePath: res.path,
					timestamp: new Date().getTime(),
					rawData: res
				};
				resolve(processedResult);
			},
			fail: (err) => {
				console.error('扫码失败:', err);
				// 扫码失败时同样返回结构化的错误信息
				const errorResult = {
					error: true,
					message: err.errMsg || '扫码失败',
					errMsg: err.errMsg,
					timestamp: new Date().getTime(),
					rawError: err
				};
				reject(errorResult);
			}
		};

		// 合并配置
		const scanOptions = {
			...defaultOptions,
			...options
		};

		uni.scanCode(scanOptions);
	});
};

// 快捷方法 - 保持原有功能但不影响主要使用方式
scanCodeUtils.weigh = (options) => scanCodeUtils(options);
scanCodeUtils.query = (options) => scanCodeUtils({
	scanType: ['code128', 'qrCode'],
	...options
});
scanCodeUtils.qrCode = (options) => scanCodeUtils({
	scanType: ['qrCode'],
	...options
});
scanCodeUtils.barcode = (options) => scanCodeUtils({
	scanType: ['code128', 'ean13'],
	...options
});

export default scanCodeUtils;